<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/1/13
 * Time: 13:35
 */

namespace app\api\service;

use app\common\exception\CustomException;
use app\common\service\platform_manage\ServerMiddlewareService;
use app\common\service\ServerUpdate;
use think\Db;
use think\exception\ValidateException;

class ServerMiddleware extends BaseService
{
    /**
     * @name 注册
     * @param $data
     * @return string
     * @author wx
     * @date 2020/1/13 15:08
     */
    public function register($data)
    {

        $params = array('name','ip','type','version');

        foreach ($params as $k => $v){
            if(!isset($data[$v])){
                throw new CustomException($v.' is must params', '202');
            }
        }

        if(count($data['ip']) == 0){
            throw new CustomException($v.' is must params', '202');
        }


        foreach ($data['ip'] as $v){
            $tmp = [
                'name' => $data['name'],
                'ip' => $v,
                'type' => $data['type'],
                'version' => $data['version'],
                'ctime' => time(),
            ];

            $insertData[] = $tmp;
        }


        Db::startTrans();
        try{
            //删除当前
            Db::name('server_middleware')->where('type', $data['type'])->delete();
            //添加
            Db::name('server_middleware')->insertAll($insertData);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            throw new CustomException('中间件注册失败', 422);
        }

        //返回监听端口
        $listenPort = Db::name('server_proxy')->where('type', $data['type'])->value('port');

        $listen = [
            'ip' => '0.0.0.0',
            'port' => $listenPort,
        ];

        //返回数据库配置
        $config = config('database.');
        $databaseConfig = [
            'ip' => $config['hostname'],
            'port' => (string) $config['hostport'],
            'user' => (string) $config['username'],
            'password' => (string) $config['password'],
            'name' => (string) $config['database'],
        ];


        $return['listen'] = $listen;
        $return['sql'] = $databaseConfig;

        return $return;
    }

    /**
     * @name
     * @param $data
     * @return array|bool|string
     * @author wx
     * @date 2020/1/13 15:01
     */
    public function getPackagePath($data)
    {
        //1. 检查同时下载客户端数量
        $updateServer = new ProductUpdate();
        $online = $updateServer->online(20);
        if(!$online){
            throw new CustomException('同时下载数量已达上限,请等待!', 422);
        }
        $data['type'] = 'middleware';

        if (!isset($data['type']) || $data['type'] != 'middleware') {
            throw new ValidateException('params error', 422);
        }

        //查询更新包数据
        $list = Db::name('server_update_list')->where('type', 'middleware')->select();

        $urlHeader = request()->domain() . '/';//协议头

        $jsonArr = array();
        foreach ($list as $k => $v){
            $v['url'] = substr($v['url'], strpos($v['url'],'public/') + strlen('public/'));
            if (file_exists($v['url'])) {
                $jsonArr[$k]['hash'] = $v['hash'];
                $jsonArr[$k]['url'] = $urlHeader.$v['url'];
                $jsonArr[$k]['name'] = $v['name'];
                $jsonArr[$k]['version'] = $v['version'];
                $jsonArr[$k]['desc'] = $v['desc'];
            }
        }

        if(empty($jsonArr)){
            throw new CustomException('当前已是最新版本', 422);
        }

        //3. 添加数据到系统更新表中
        $ip = $_SERVER['REMOTE_ADDR'];//客户端ip

        $server = new ServerUpdate();
        $data_info = $server->findData(['ip' => $ip]);
        if($data_info){
            $updateData = array(
                'status' => 1,
                'last_time' => time(),
            );
            $server->modify(['id' => $data_info['id']], $updateData);
        }else{
            $addData = array(
                'ip' => $ip,
                'status' => 1,
                'last_time' => time(),
                'ctime' => time(),
            );
            $server->add($addData);
        }

        //4. 返回数据
        return $jsonArr;
    }
}